package com.zzptc.easyshop.servlet;

import com.zzptc.easyshop.dao.IDAO;
import com.zzptc.easyshop.dao.ProductDao;
import com.zzptc.easyshop.util.ShopCarUtil;
import com.zzptc.easyshop.vo.Product;
import com.zzptc.easyshop.vo.ShopCarGood;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShopCartServlet")
public class ShopCartServlet extends HttpServlet {
    List<ShopCarGood> cartlist ;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        int id = 0;
        if (request.getParameter( "id" )!=null) {
            id = Integer.parseInt( request.getParameter( "id" ) );
        }
        IDAO dao = new ProductDao();

        Product  product = null;
        try {
            product = ((ProductDao) dao).getProductByid(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //1.每个人只能有一个购物车，2.购物车是什么？？
        if (cartlist==null){
            cartlist = new ArrayList<ShopCarGood>();
        }
        ShopCarGood shopCarGood = new ShopCarGood();
        shopCarGood.setId(product.getEp_id());
        shopCarGood.setName(product.getEp_name());
        shopCarGood.setPrice( product.getEp_price() );
        shopCarGood.setEp_file_name( product.getEp_file_name());
        shopCarGood.setNum( 1 );
        ShopCarUtil.addGood( shopCarGood,cartlist );
        //换一个作用域
        HttpSession se =request.getSession();
        se.setAttribute( "shop",cartlist );
        response.sendRedirect( "shopping.jsp" );



    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost( request,response );
    }
}
